package com.hz.controller;

import com.hz.pojo.Book;
import com.hz.pojo.Result;
import com.hz.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean save = bookService.save(book);
        int code=save? 200 : 404;
        return new Result(code,save);
    }
    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);

        int code=book!=null?200:404;

        String msg=book!=null?"查询成功":"查询失败";
        return new Result(code,book,msg);
    }

    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }


    @PostMapping("/doimg")
    public void DoImg(@RequestParam("img") MultipartFile file) throws IOException {
        //获取当前文件名
        String originalFilename = file.getOriginalFilename();
        //使用uuid作为文件名解决重复问题
        String uuid = UUID.randomUUID().toString();
        //获取文件名的后缀名,拼接新文件名
        String newFileName =uuid+ originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置文件存储位置
        file.transferTo(new File("E:\\img\\"+newFileName));
    }
}
